package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @version 1.0
 * @Author 郭腾高
 * @Date 2024/9/7 21:51
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //1.获取请求url
        String url = req.getRequestURI().toString();
        //2.判断url中是否包含login，包含就放行
        if(url.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.获取请求头的令牌
        String jwt = req.getHeader("token");
        //4.判断jwt令牌是否为null或空串

        if(!StringUtils.hasLength(jwt)){
            //JWT为空
            Result error = Result.error("NOT_LOGIN");
            //响应json数据 手动转换对象---》json数据  ---导入fastJSON
            String jsonString = JSONObject.toJSONString(error);
            //响应json数据给浏览器
            resp.getWriter().write(jsonString);
            return;
        }
        //5.解析jwt，如果解析失败返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//如果出现异常，就说明解析失败
            e.printStackTrace();
            //JWT为空
            Result error = Result.error("NOT_LOGIN");
            //响应json数据 手动转换对象---》json数据
            String jsonString = JSONObject.toJSONString(error);
            //响应json数据给浏览器
            resp.getWriter().write(jsonString);
            return;
        }
        //6.放行
        filterChain.doFilter(servletRequest,servletResponse);

    }




}
